<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">

      <el-form-item label="科室名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择所属医院" size="small">
          <el-option
            v-for="item in hospitalList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status" @change="handleQuery">
          <el-radio-button :label="undefined">全部</el-radio-button>
          <el-radio-button label="active">启用</el-radio-button>
          <el-radio-button label="inactive">禁用</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:department:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:department:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('active')"
          v-hasPermi="['biz:department:changeStatusBatch']"
        >批量启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('inactive')"
          v-hasPermi="['biz:department:changeStatusBatch']"
        >批量禁用
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="departmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="科室名称" align="center" prop="departmentName">
        <template slot-scope="scope">
          <span style="cursor: pointer;color: #1c84c6;" @click="goDetail(scope.row)"
                v-hasPermi="['biz:department:query']"
          >{{ scope.row.departmentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属医院" align="center" prop="hospitalName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 'active'" style="color: green">启用</span>
          <span v-if="scope.row.status === 'inactive'" style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.status==='inactive'"
            size="mini"
            type="text"
            icon="el-icon-check"
            style="color: #4AB7BD"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:department:changeStatus']"
          >启用
          </el-button>
          <el-button
            v-show="scope.row.status==='active'"
            size="mini"
            type="text"
            icon="el-icon-close"
            style="color: #E65D6E"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:department:changeStatus']"
          >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:department:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改科室对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="85px" style="margin-left: 20px">
        <el-form-item label="科室Logo" prop="departmentLogo">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            name="multipartFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.departmentLogo" :src="form.departmentLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="color: red">推荐上传jpg、png、jpeg文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="科室名称" prop="departmentName">
          <el-input v-model="form.departmentName" maxlength="30" placeholder="请输入科室名称" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择所属医院" style="width: 70%">
            <el-option
              v-for="item in hospitalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="active">启用</el-radio-button>
            <el-radio-button label="inactive">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" maxlength="255" placeholder="请输入备注" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="科室简介" prop="departmentIntroduction">
          <Editor v-model="form.departmentIntroduction" style="height: 300px;width: 95%"/>
          <!--          <UEditor  :editor-content="form.departmentIntroduction"  @updateContent="val => {this.form.departmentIntroduction = val;}"/>-->
          <!--          <UEditor :editorContent="form.departmentIntroduction" @updateContent="updateContent"></UEditor>-->
        </el-form-item>
      </el-form>
      <div style="text-align: center;margin-top: 70px">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <el-drawer
      title="科室详情"
      :visible.sync="drawer"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      append-to-body
    >
      <div class="imageDiv">
        <el-image :src="form.departmentLogo" style="height: 100px"></el-image>
      </div>
      <div style="height:100px;width:300px;" class="dd">
        <p style="margin: 10px 5px">科室名称：{{ form.departmentName }}</p>
        <p style="margin-left: 5px">所属医院：{{ form.hospitalName }}</p>
      </div>
      <div style="height: 100px">
        <span v-if="form.status === 'active'" style="color: green">启用</span>
        <span v-if="form.status === 'inactive'" style="color:red;">禁用</span>
        <div>
          <el-button
            type="primary"
            style="margin-left: 200px"
            @click="handleEdit"
            v-hasPermi="['biz:department:edit']"
          >编辑
          </el-button>
          <el-button
            type="success"
            style="margin-left: 20px"
            v-if="form.status === 'inactive'"
            @click="handleUpdateStatus(form.id,form.status)"
            v-hasPermi="['biz:department:changeStatus']"
          >启用
          </el-button>

          <el-button
            type="danger"
            style="margin-left: 20px"
            @click="handleUpdateStatus(form.id,form.status)"
            v-if="form.status === 'active'"
            v-hasPermi="['biz:department:changeStatus']"
          >禁用
          </el-button>
        </div>

      </div>

      <div style="margin: 20px 20px">
        <el-tabs v-model="activeName">
          <el-tab-pane label="简介" name="introduction">
            <el-button
              type="primary"
              style="margin-left: 85%"
              @click="handleEdit"
              v-hasPermi="['biz:department:edit']"
            >修改简介
            </el-button>
            <span v-html="form.departmentIntroduction"></span>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listDepartment,
  getDepartment,
  delDepartment,
  addDepartment,
  updateDepartment,
  changeStatus
} from '@/api/biz/department'
import { listAllHospital } from '@/api/biz/hospital'
import { getToken } from '@/utils/auth'
import UEditor from '@/components/UEditor'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'Department',
  components: {
    UEditor,
    ElImageViewer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科室表格数据
      departmentList: [],
      hospitalList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      drawer: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        departmentName: undefined,
        departmentLogo: undefined,
        departmentIntroduction: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      submitLoading: false,
      // 表单校验
      rules: {
        hospitalId: [
          { required: true, message: '医院id不能为空', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '科室名称不能为空', trigger: 'blur' }
        ],
        departmentLogo: [
          { required: true, message: '科室Logo不能为空', trigger: 'blur' }
        ]
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/uploadObs'
      },
      activeName: 'introduction'
    }
  },
  created() {
    this.getList()
    this.getAllHospitalList()
  },
  methods: {
    /** 查询科室列表 */
    getList() {
      this.loading = true
      listDepartment(this.queryParams).then(response => {
        this.departmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getAllHospitalList() {
      listAllHospital().then(res => {
        console.log('res', res)
        this.hospitalList = res.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    getIndex($index) {
      //表格序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hospitalId: null,
        departmentName: null,
        departmentLogo: null,
        departmentIntroduction: null,
        status: 'active',
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加科室'
    },
    handleChangeStatus(row) {
      let statusText = row.status === 'active' ? '禁用' : '启用'
      let status = row.status === 'active' ? 'inactive' : 'active'
      const ids = [row.id] || this.ids
      this.$confirm('是否确认' + statusText + '该项数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },
    /**详情中启用禁用*/
    handleUpdateStatus(id, status) {
      let statusText = status === 'active' ? '禁用' : '启用'
      status = status === 'active' ? 'inactive' : 'active'
      const ids = [id] || this.ids
      this.$confirm('是否确认' + statusText + '该项数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.form.status = status
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },
    handleBatchChangeStatus(status) {
      let statusText = status === 'active' ? '启用' : '禁用'
      const ids = this.ids
      this.$confirm('是否确认' + statusText + '选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDepartment(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改科室'
      })
    },
    /**详情中编辑*/
    handleEdit() {
      this.drawer = false
      this.open = true
      this.title = '修改科室'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id != null) {
            updateDepartment(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          } else {
            addDepartment(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除科室编号为"' + ids + '"的数据项？').then(function() {
        return delDepartment(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('biz/department/export', {
        ...this.queryParams
      }, `department_${new Date().getTime()}.xlsx`)
    },
    handleAvatarSuccess(res, file) {
      this.form.departmentLogo = res.data.url
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    updateContent(content) {
      this.form.departmentIntroduction = content
    },
    /**详情*/
    goDetail(row) {
      //this.activeName = 'baseInfo';
      getDepartment(row.id).then(response => {
        this.form = response.data
        this.drawer = true
      })

    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dd {
  width: 200px;
  float: left;
}

.level {
  margin-left: 17px;
  width: 80px;
  height: 35px;
  text-align: center;
  line-height: 35px;
  margin-top: 20px
}

.imageDiv {
  width: 150px;
  height: 100px;
  float: left;
  margin-left: 17px;
}
</style>
